package com.xwj.service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xwj.dao.ItemDao;
import com.xwj.domain.Item;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author xwj
 * @date 2020/4/27
 */
@Service
public class CacheItemService {
    @Autowired
    private ItemDao itemDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    private static final String key_item_prefix = "item:";

    public Item getItemByCode(String code) throws Exception {
        Item item = null;
        final String key = key_item_prefix + code;
        ValueOperations operations = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(key)) {
            Object val = operations.get(key);
            if(!StringUtils.isEmpty(val)) {
                item = objectMapper.readValue(val.toString(), Item.class);
            }
        } else {
            item = itemDao.getItemByCode(code);
            if (item == null) {
                operations.set(key, "", 30L, TimeUnit.SECONDS);
            } else {
                operations.set(key, objectMapper.writeValueAsString(item));
            }
        }
        return item;
    }
}
